//
//  NewsDetailController.swift
//  Jock
//
//  Created by HD on 15/3/19.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

class NewsDetailController: UIViewController, UITableViewDataSource, UITableViewDelegate, RefreshViewDelegate, UITextViewDelegate {
    
    var news: News?
    
    private var tableView: UITableView?
    private let identifier = "cell"
    
    private var commentEditView: CommentEditView?
    
    private var page: Int = 1
    private var isLoading = false
    private var isGetAll = false
    
    private let httpClient = HttpClient()
    
    private var data: [NewsComment] = [NewsComment]()
    
    private var refreshView: JockRefreshView?
    private var headerView: DetailHeaderView?
    private var footerView: UIView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "糗事\(news!.id)"
        initView()
        initData()
    }
    
    // 初始化界面
    private func initView() {
        // add table view
        tableView = UITableView(frame: CGRectMake(0, 0, view.frame.width, view.frame.height - 46))
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.registerNib(UINib(nibName:"NewsCommentCell", bundle: nil), forCellReuseIdentifier: identifier)
        
        refreshView = ViewUtil.instanceView("JockRefreshView") as? JockRefreshView
        let refreshHeight:CGFloat = 81
        refreshView?.frame = CGRectMake(0, -refreshHeight, view.frame.width, refreshHeight)
        refreshView?.delegate = self
        refreshView?.refreshTriggerHeight = refreshHeight
        refreshView?.refreshNormalHeight = -64
        tableView?.addSubview(refreshView!)
        
        headerView = ViewUtil.instanceView("DetailHeaderView") as? DetailHeaderView
        let height = news?.content.stringHeightWith(16, width: view.frame.width - 16)
        headerView?.frame = CGRectMake(0, 0, view.frame.width, 98 + height!)
        tableView?.tableHeaderView = headerView
        
        footerView = ViewUtil.instanceView("FooterView")
        footerView?.frame = CGRectMake(0, 0, view.frame.width, 56)
        tableView?.tableFooterView = footerView
        view.addSubview(tableView!)
        
        
        // add comment view
        commentEditView = ViewUtil.instanceView("CommentEditView") as? CommentEditView
        commentEditView?.frame = CGRectMake(0, tableView!.frame.height, view.frame.width, 46)
        commentEditView?.textView.delegate = self
        commentEditView?.textView.autoresizingMask = UIViewAutoresizing.FlexibleHeight
        commentEditView?.commentBtn.addTarget(self, action: "commentAction", forControlEvents: .TouchUpInside)
        self.view.addSubview(commentEditView!)
    }
    
    // 初始化数据
    private func initData() {
        setHeaderData()
        registerForKeyboardNotifications()
        refreshView?.startRefresh()
    }
    
    func commentAction() {
        var commentStr = commentEditView!.textView.text
        println(commentStr)
        self.commentEditView?.textView.resignFirstResponder()
    }
    
    // 自动控制TextView的高度
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if textView.contentSize.height <= 120 && textView.textLine > 1 {
            let bottom = self.commentEditView!.getBottom()
            self.commentEditView!.setY(bottom - textView.contentSize.height - 16)
            self.commentEditView!.setHeight(textView.contentSize.height + 16)
        } else if textView.textLine == 1 {
            self.commentEditView!.setY(self.commentEditView!.getBottom() - 46)
            self.commentEditView?.setHeight(46)
        }
        return true
    }
    
    func textViewDidChange(textView: UITextView) {
        var offset = textView.contentOffset
        offset.y = textView.contentSize.height - textView.frame.height
        textView.contentOffset = offset
    }
    
    func registerForKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasHidden:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func keyboardWasShown(notification: NSNotification) {
        let info = notification.userInfo
        let size = info?[UIKeyboardFrameEndUserInfoKey]!.CGRectValue().size
        let duration = info?[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        UIView.animateWithDuration(duration!, animations: { () -> Void in
            self.commentEditView!.setY(self.view.frame.height - size!.height - 46)
        })
    }

    func keyboardWasHidden(notification: NSNotification) {
        let info = notification.userInfo
        let duration = info?[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        self.commentEditView?.textView.text = ""
        self.commentEditView?.setHeight(46)
        UIView.animateWithDuration(duration!, animations: { () -> Void in
            self.commentEditView!.setY(self.view.frame.height - 46)
        })
    }
    
    //显示headerView的数据
    func setHeaderData() {
        headerView?.news = news
        let contentHeight = self.news?.content.stringHeightWith(16, width: self.view.frame.width - 16)
        var height = news?.image_size != nil ? CGFloat(news!.image_size.m.height) * (self.view.frame.width - CGFloat(16)) / CGFloat(news!.image_size.m.width) : 0
        if let image = news!.image {
            height += 97
        } else {
            height += 89
        }
        self.headerView?.setHeight(height + contentHeight!)
        self.tableView?.tableHeaderView = self.headerView
        headerView?.showData()
    }
    
    func pushToRefresh() {
        refreshView!.refreshLabel.text = "下拉刷新"
        refreshView?.refreshIndicator.hidden = true
        refreshView?.refreshIndicator.stopAnimating()
    }
    
    func releaseToRefresh() {
        refreshView!.refreshLabel.text = "释放刷新"
    }
    
    func pushOffset(offset: CGFloat) {
    }
    
    func refresh() {
        refreshView?.refreshIndicator.hidden = false
        refreshView?.refreshIndicator.startAnimating()
        refreshView?.refreshLabel.text = "正在刷新"
        page = 1
        loadData(true)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as? NewsCommentCell
        cell?.comment = self.data[indexPath.row]
        cell?.show()
        return cell!
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let contentHeight = data[indexPath.row].content.stringHeightWith(16, width: self.view.frame.width)
        return 64 + contentHeight
    }
    
    private func loadData(refresh: Bool) {
        isLoading = true
        HttpClient().Get("http://m2.qiushibaike.com/article/\(news!.id)/comments?count=20&page=\(self.page)", response: { (response) -> Void in
            if response.data != nil {
                let json = JSON(data: response.data!)
                if refresh {
                    self.data.removeAll(keepCapacity: false)
                }
                var newData = NewsComment.analyse(json)
                self.data += newData
                if newData.count < 20 {
                    self.isGetAll = true
                }
                newData.removeAll()
                self.tableView?.reloadData()
                self.refreshView?.endRefresh()
                self.isLoading = false
            } else {
                println("data is nil")
            }
        }) { (error) -> Void in
            println("error")
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.height && !isLoading && !isGetAll {
            page++
            loadData(false)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}
